// pages/select-lesson/select-lesson.js
var app = getApp()
Page({

    /**
     * Page initial data
     */
    data: {
        changed: Object,
        organizations:[],
        ratioIdx: 0
    },

    /**
     * Lifecycle function--Called when page load
     */
    onLoad(options) {
        this.setData(
            {
                changed: new Map()
            }
        )
        var orgInfo = app.getorginfo()
        if (orgInfo) {
            for (var i = 0; i < orgInfo.length; i++) {
                for (var j = 0; j < orgInfo[i].lessons.length; j++) {
                    orgInfo[i].lessons[j].checked = false
                }
            }
            this.setData(
                {
                    organizations: orgInfo
                }
            )
            console.log(orgInfo)
            return
        } else {
            wx.reLaunch({
              	url: '../index/index',
            })
        }
    },
    checkboxChange(e) {
        var index = e.currentTarget.dataset.id - 1
        if (e.detail.value.length > 1) {
            wx.showToast({
                title: '同一个机构只能选一门课程, 请重新选择',
                icon: 'none'
            })
        }
        this.data.changed.set(index, e.detail.value)
    },
    onCheckLesson() {
        var hasErr = false
        var lessonIdx = []
        this.data.changed.forEach((val, key) => {
            if (val.length > 1) {
                hasErr = true;
            } else if (val.length == 1) {
                lessonIdx.push(val[0])
            }
       })
       if (hasErr) {
            wx.showToast({
                title: '同一个机构只能选一门课程, 请重新选择',
                icon: 'none'
            })
       } else {
           if (lessonIdx.length > 4) {
                wx.showToast({
                    title: '最多只能选择4门课程，请重新选择',
                    icon: 'none'
                })
           } else if (lessonIdx.length == 0) {
                wx.showToast({
                    title: '最少选择1门课程，请重新选择',
                    icon: 'none'
                })
           } else {
                wx.redirectTo({
                  url: '../buy-lesson/buy-lesson?lesson=' + lessonIdx.join('_')
                })
           }
       }
    },

    /**
     * Lifecycle function--Called when page is initially rendered
     */
    onReady() {

    },

    /**
     * Lifecycle function--Called when page show
     */
    onShow() {

    },

    /**
     * Lifecycle function--Called when page hide
     */
    onHide() {

    },

    /**
     * Lifecycle function--Called when page unload
     */
    onUnload() {

    },

    /**
     * Page event handler function--Called when user drop down
     */
    onPullDownRefresh() {

    },

    /**
     * Called when page reach bottom
     */
    onReachBottom() {

    },

    /**
     * Called when user click on the top right corner to share
     */
    onShareAppMessage() {

    }
})